#import "WalkMap.h"
#import "Entity.h"
#import "Tile.h"
#import "Shop.h"
#import "Item.h"
#import "Gateway.h"
#import "State.h"
#define DOUBLE_TAP_DELAY 0.35

CGPoint midpointBetweenPoints(CGPoint a, CGPoint b);

@interface WalkMap ()
- (void)handleSingleTap;
- (void)handleDoubleTap;
- (void)handleTwoFingerTap;
@end

@implementation WalkMap
@synthesize delegate,tiles,tileSet,spriteSet,spriteSize,tileSize,people,player;
@synthesize shops,shopSet,itemSet,items,gateways,gatewaySet;
-(id) initWithBackground:(NSString*)name{
back=[UIImage imageNamed:name];
self = [super initWithFrame:CGRectMake(0, 0, back.size.width, back.size.height)];
	self.backgroundColor=[UIColor colorWithWhite:1.0 alpha:1.0];
	[back retain];
	[self setUserInteractionEnabled:YES];
	[self setMultipleTouchEnabled:YES];
	twoFingerTapIsPossible = YES;
	multipleTouches = NO;
	for (int i =0; i<100; i++) {
		for (int j=0;j<100;j++){
			tileMap[i][j]=TILE_EMPTY;
		}
	}
	return self;
}
-(int)getType:(int)x y:(int)y{
	return tileMap[x][y];
}
-(void)setType:(int)tile x:(int)x y:(int)y{
	tileMap[x][y]=tile;
}

-(int)stateMachine{
	int dx = goal.x -player.center.x; 
	int dy = goal.y -player.center.y;
	int tileX=player.center.x/tileSize; 
	int tileY=player.center.y/tileSize;
	
	if (dx >10){
		if(tileMap[tileX+1][tileY]==TILE_EMPTY) {
		dx =10;
		dy=0;
		player.movement=MOVE_RIGHT;
		}else if(tileMap[tileX+1][tileY]==TILE_GATEWAY){
			return S_MAP_DUNGEON;
			
		}

	}else if(dx < -10  && tileMap[tileX-1][tileY]==TILE_EMPTY){
		//move left
		dx=-10;
		dy=0;
		player.movement=MOVE_LEFT;
	}else{
		dx=0;
		if (dy >10  && tileMap[tileX][tileY+1]==TILE_EMPTY) {
			//move down
			dy =10;
			player.movement=MOVE_DOWNWARD;
		}else if (dy < -10  && tileMap[tileX][tileY-1]==TILE_EMPTY){
			//move up
			dy=-10;
			player.movement=MOVE_UPWARD;


		}
		else {
			dy=0;
		}

	}
	player.center=CGPointMake(player.center.x+dx,player.center.y+dy);
	if(dx==0 && dy==0)
		goal=player.center;
	
	
	
	[self setNeedsDisplay];
	[player setNeedsDisplay];
	for(int i=0;i<[self.people count];i++)
	{
		Entity* e= [people objectAtIndex:i];
		[e setNeedsDisplay];
		
	}
	return S_MAP_TOWN;
}

-(void)drawRect:(CGRect)rect{
	[back drawAtPoint:CGPointMake(0, 0)];
	[super drawRect:rect];
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // cancel any pending handleSingleTap messages 
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(handleSingleTap) object:nil];
    
    // update our touch state
    if ([[event touchesForView:self] count] > 1)
        multipleTouches = YES;
    if ([[event touchesForView:self] count] > 2)
        twoFingerTapIsPossible = NO;
    
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    BOOL allTouchesEnded = ([touches count] == [[event touchesForView:self] count]);
    
    // first check for plain single/double tap, which is only possible if we haven't seen multiple touches
    if (!multipleTouches) {
        UITouch *touch = [touches anyObject];
        tapLocation = [touch locationInView:self];
        
        if ([touch tapCount] == 1) {
            [self performSelector:@selector(handleSingleTap) withObject:nil afterDelay:DOUBLE_TAP_DELAY];
        } else if([touch tapCount] == 2) {
            [self handleDoubleTap];
        }
    }    
    
    // check for 2-finger tap if we've seen multiple touches and haven't yet ruled out that possibility
    else if (multipleTouches && twoFingerTapIsPossible) { 
        
        // case 1: this is the end of both touches at once 
        if ([touches count] == 2 && allTouchesEnded) {
            int i = 0; 
            int tapCounts[2]; CGPoint tapLocations[2];
            for (UITouch *touch in touches) {
                tapCounts[i]    = [touch tapCount];
                tapLocations[i] = [touch locationInView:self];
                i++;
            }
            if (tapCounts[0] == 1 && tapCounts[1] == 1) { // it's a two-finger tap if they're both single taps
                tapLocation = midpointBetweenPoints(tapLocations[0], tapLocations[1]);
                [self handleTwoFingerTap];
            }
        }
        
        // case 2: this is the end of one touch, and the other hasn't ended yet
        else if ([touches count] == 1 && !allTouchesEnded) {
            UITouch *touch = [touches anyObject];
            if ([touch tapCount] == 1) {
                // if touch is a single tap, store its location so we can average it with the second touch location
                tapLocation = [touch locationInView:self];
            } else {
                twoFingerTapIsPossible = NO;
            }
        }
		
        // case 3: this is the end of the second of the two touches
        else if ([touches count] == 1 && allTouchesEnded) {
            UITouch *touch = [touches anyObject];
            if ([touch tapCount] == 1) {
                // if the last touch up is a single tap, this was a 2-finger tap
                tapLocation = midpointBetweenPoints(tapLocation, [touch locationInView:self]);
                [self handleTwoFingerTap];
            }
        }
    }
	
    // if all touches are up, reset touch monitoring state
    if (allTouchesEnded) {
        twoFingerTapIsPossible = YES;
        multipleTouches = NO;
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    twoFingerTapIsPossible = YES;
    multipleTouches = NO;
}


#pragma mark Private

- (void)handleSingleTap {
    if ([delegate respondsToSelector:@selector(tapWalkMap:gotSingleTapAtPoint:)])
        [delegate tapWalkMap:self gotSingleTapAtPoint:tapLocation];
}

- (void)handleDoubleTap {
    if ([delegate respondsToSelector:@selector(tapWalkMap:gotDoubleTapAtPoint:)])
        [delegate tapWalkMap:self gotDoubleTapAtPoint:tapLocation];
}

- (void)handleTwoFingerTap {
    if ([delegate respondsToSelector:@selector(tapWalkMap:gotTwoFingerTapAtPoint:)])
        [delegate tapWalkMap:self gotTwoFingerTapAtPoint:tapLocation];
}

@end

CGPoint midpointBetweenPoints(CGPoint a, CGPoint b) {
    CGFloat x = (a.x + b.x) / 2.0;
    CGFloat y = (a.y + b.y) / 2.0;
    return CGPointMake(x, y);
}
      
//@end